package com.ruoyi.system.waishu;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 业务调用类
 */
@Component
@Slf4j
public class YewuService {

    @Autowired
    InvokeService invokeService;

    //1.实现一个自己的线程池工厂
    ThreadFactory factory = (Runnable r) -> {
        //创建一个线程
        Thread t = new Thread(r);
        //给创建的线程设置UncaughtExceptionHandler对象 里面实现异常的默认逻辑
        t.setDefaultUncaughtExceptionHandler((Thread thread1, Throwable e) -> {
            // 在此设置统计监控逻辑
            System.out.println("线程工厂设置的exceptionHandler" + e.getMessage());
        });
        return t;
    };

    // 2.创建一个自己定义的线程池，使用自己定义的线程工厂
    ExecutorService service = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>(10),factory);

    public JSONObject invoke(TableDo tableDo){
        long start = System.currentTimeMillis();
        HashMap<String, Object> map = new HashMap<>();
        ConcurrentHashMap<String, String> params = new ConcurrentHashMap<>();
        AbstractRequest request = new AbstractRequest(tableDo.getKeyId(),map,tableDo.getKeyId());
        Map<String, Future<JSONObject>> future = new HashMap<>();
        JSONObject response = new JSONObject();
        ServiceIdEnum.jbloan().forEach(s->{
            future.put(s.getServiceId(),service.submit(new ThirdEvent(request,tableDo,params,s,invokeService)));
        });
        future.forEach((v1,v2)->{
            try {
                response.put(v1,v2.get());
            } catch (Exception e) {
                log.error("{}获取外数服务结束异常",tableDo.getKeyId(),e);
            }
        });
        log.info("{}耗时{}s外数结果：{}",tableDo.getKeyId(),(System.currentTimeMillis()-start)/1000,response);
        tableDo.setThirdData(response);
        return response;
    }
}
